package com.sailors.common.task.provider.application.convert;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sailors.common.task.provider.infra.design.common.util.calculate.Exp4jUtil;
import com.sailors.common.task.provider.infra.repository.factories.FileTaskRepositoryFactory;
import com.sailors.common.task.provider.infra.repository.ITaskProLogRepository;
import com.sailors.common.task.provider.infra.repository.model.FileTaskLogPo;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
import com.sailors.common.task.provider.faced.model.vo.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * File task agg conver
 *
 * @description:
 * @author: cyj
 * @date 2023 -02-22 00:19:06
 */
@Mapper
public interface FileTaskAggConver {
    /**
     * 默认的方式
     */
    FileTaskAggConver INSTANCE = Mappers.getMapper(FileTaskAggConver.class);

    @Mappings({
    })
    Page<FileTaskLogDetailVo> fileTaskLogPoPage2Vo(Page<FileTaskLogPo> fileTaskLogPoPage);

    @AfterMapping
    default void fileTaskLogPoPage2Vo(@MappingTarget Page<FileTaskLogDetailVo> detailVoPage, Page<FileTaskLogPo> fileTaskLogPoPage) {
        List<FileTaskLogDetailVo> records = detailVoPage.getRecords();
        if(CollectionUtils.isNotEmpty(records)) {
            List<Long> taskIds = records.stream().map(FileTaskLogDetailVo::getId).collect(Collectors.toList());
            List<TaskProLogVo> taskProLogVos = FileTaskRepositoryFactory.getRepository(ITaskProLogRepository.class).getByTaskIds(taskIds);
            Map<Long, List<TaskProLogVo>> taskProLogMaps = taskProLogVos.stream().collect(Collectors.groupingBy(TaskProLogVo::getTaskId));

            // 计算进度
            records.stream().forEach(fileTaskLogDetailVo -> {
                List<TaskProLogVo> process = taskProLogMaps.getOrDefault(fileTaskLogDetailVo.getId(), new ArrayList<>());
                //fileTaskLogDetailVo.setTaskProLogVos(process);
                if (CollectionUtils.isEmpty(process)) {
                    fileTaskLogDetailVo.setFinishCount(0L);
                    fileTaskLogDetailVo.setNowProcess(BigDecimal.ZERO);
                } else {
                    fileTaskLogDetailVo.setNowProcess(process.get(0).getProcess());
                    BigDecimal finishCount = Exp4jUtil.calculateCommon(fileTaskLogDetailVo);
                    fileTaskLogDetailVo.setFinishCount(null == finishCount ? 0L : finishCount.longValue());
                }
            });
        }
    }

}
